"""
用户模型
"""
from sqlalchemy import Column, String, Boolean, Enum as SQLEnum
from sqlalchemy.orm import relationship
import enum

from app.models.base import BaseModel


class UserRole(str, enum.Enum):
    """用户角色枚举"""
    ADMIN = "admin"           # 管理员
    CUSTOMER = "customer"     # 普通客户
    VIP = "vip"              # VIP会员
    GUEST = "guest"          # 访客


class UserStatus(str, enum.Enum):
    """用户状态枚举"""
    ACTIVE = "active"         # 活跃
    INACTIVE = "inactive"     # 未激活
    BANNED = "banned"         # 封禁
    DELETED = "deleted"       # 已删除


class User(BaseModel):
    """用户模型"""
    
    __tablename__ = "users"
    
    # 基本信息
    username = Column(String(50), unique=True, index=True, nullable=False, comment="用户名")
    email = Column(String(100), unique=True, index=True, nullable=True, comment="邮箱")
    phone = Column(String(20), unique=True, index=True, nullable=True, comment="手机号")
    hashed_password = Column(String(255), nullable=False, comment="密码哈希")
    
    # 用户属性
    full_name = Column(String(100), nullable=True, comment="真实姓名")
    avatar = Column(String(255), nullable=True, comment="头像URL")
    role = Column(
        SQLEnum(UserRole),
        default=UserRole.CUSTOMER,
        nullable=False,
        comment="用户角色"
    )
    status = Column(
        SQLEnum(UserStatus),
        default=UserStatus.ACTIVE,
        nullable=False,
        comment="用户状态"
    )
    
    # 会员信息
    is_vip = Column(Boolean, default=False, comment="是否VIP会员")
    vip_expire_at = Column(String(50), nullable=True, comment="VIP过期时间")
    points = Column(String(20), default="0", comment="积分")
    
    # 统计信息
    login_count = Column(String(20), default="0", comment="登录次数")
    last_login_at = Column(String(50), nullable=True, comment="最后登录时间")
    last_login_ip = Column(String(50), nullable=True, comment="最后登录IP")
    
    # 关系
    conversations = relationship(
        "Conversation",
        back_populates="user",
        cascade="all, delete-orphan"
    )
    orders = relationship(
        "Order",
        back_populates="user",
        cascade="all, delete-orphan"
    )
    
    def __repr__(self):
        return f"<User(id={self.id}, username={self.username}, role={self.role})>"
    
    @property
    def is_active(self) -> bool:
        """是否活跃"""
        return self.status == UserStatus.ACTIVE
    
    @property
    def is_admin(self) -> bool:
        """是否管理员"""
        return self.role == UserRole.ADMIN

